#!/usr/bin/env bash
# ══════════════════════════════════════════════════════════════════════════════
# 🐾 FurryOS Gen2.1_v2 Master Build System: Sovereign Universe
# ══════════════════════════════════════════════════════════════════════════════
# Lead Architect: Thomas B. Sweet (Anthro Entertainment LLC)
# Lore: AnthroHeart Saga / Warlock Name Universe (est. 2004)
# Features: 75% RAM Safety, DNS Persistence, Ember-Night UI, Master Tempter Lore
# ══════════════════════════════════════════════════════════════════════════════

BUILD_START_TIME=$(date +%s)
set -e

# ------------------------------------------------------------------------------
# [Phase 0] Path & Resource Configuration
# ------------------------------------------------------------------------------
PROJECT_ROOT="$(cd "$(dirname "$0")" && pwd)"
PARENT_DIR="$(cd "$PROJECT_ROOT/.." && pwd)"
GENERATED="$PARENT_DIR/_generated"
BUILD_DIR="$PARENT_DIR/build"
ISO_DIR="$GENERATED/iso"
WORK_DIR="$GENERATED/work"
ISO_ROOT="$GENERATED/iso-root"
SQUASHFS_ROOT="$WORK_DIR/squashfs-root"
OUTPUT_DIR="$BUILD_DIR/output"

# Auto-log every byte of the transformation
exec > >(tee -a "build_$(date +%Y%m%d_%H%M%S).log") 2>&1

echo "╔════════════════════════════════════════════════════════════╗"
echo "║   🐾 FurryOS Gen2.1_v2: Sovereign Universe Build Engine    ║"
echo "╚════════════════════════════════════════════════════════════╝"

# Calculate system limits for the "Next Octave" (YouTube-safe)
if command -v free >/dev/null 2>&1; then
    AVAIL_GB=$(free --giga | awk '/^Mem:/ {print int($7)}')
    SQUASH_MEM=$((AVAIL_GB * 75 / 100))
    [ "$SQUASH_MEM" -lt 2 ] && SQUASH_MEM=2
    echo "📊 System Capacity: ${AVAIL_GB}G avail -> Using ${SQUASH_MEM}G for compression."
else
    SQUASH_MEM="4"
fi

# Cleanup/Keep Menu
echo "Selection: [C]lean Everything | [K]eep Folders (Incremental) | [D] Keep ISO Only"
read -p "Selection [C]: " -n 1 -r BUILD_MODE
echo ""
case ${BUILD_MODE,,} in
    k ) echo "➡️  KEEP MODE: Skipping extraction for maximum speed..."; ;;
    d ) sudo umount -l "$SQUASHFS_ROOT" "$ISO_ROOT" 2>/dev/null || true
        sudo rm -rf "$WORK_DIR" "$ISO_ROOT";;
    * ) sudo umount -l "$SQUASHFS_ROOT" "$ISO_ROOT" 2>/dev/null || true
        sudo rm -rf "$BUILD_DIR" "$GENERATED" "$WORK_DIR" "$ISO_ROOT";;
esac

mkdir -p "$OUTPUT_DIR" "$ISO_DIR" "$WORK_DIR" "$ISO_ROOT"

# ------------------------------------------------------------------------------
# [Phase 1] Base System Extraction (The "Unpacking" of Trauma)
# ------------------------------------------------------------------------------
ISO_FILE="$ISO_DIR/debian-live-mate-amd64.iso"
if [ ! -f "$ISO_FILE" ]; then
    echo "⬇️ Downloading Debian 13 Base..."
    curl -L "https://cdimage.debian.org/debian-cd/current-live/amd64/iso-hybrid/debian-live-13.2.0-amd64-mate.iso" -o "$ISO_FILE"
fi

# Smart Skip for ISO extraction
if [[ ${BUILD_MODE,,} == "k" && -d "$ISO_ROOT/live" ]]; then
    echo "✅ ISO structure grounded. Skipping extraction."
else
    echo "[Phase 1.1] Extracting ISO structure..."
    sudo rm -rf "$ISO_ROOT" && mkdir -p "$ISO_ROOT"
    sudo bsdtar -C "$ISO_ROOT" -xf "$ISO_FILE"
fi

# Smart Skip for Filesystem extraction
if [[ ${BUILD_MODE,,} == "k" && -d "$SQUASHFS_ROOT/etc" ]]; then
    echo "✅ Filesystem grounded. Skipping unsquash."
else
    echo "[Phase 1.2] Extracting Master Filesystem (This is the heavy unpacking)..."
    sudo rm -rf "$SQUASHFS_ROOT" && mkdir -p "$SQUASHFS_ROOT"
    sudo unsquashfs -f -d "$SQUASHFS_ROOT" "$ISO_ROOT/live/filesystem.squashfs"
    sudo chown -R "$USER":"$USER" "$SQUASHFS_ROOT"
fi

# ------------------------------------------------------------------------------
# [Phase 2] High-Density Chroot Bridge
# ------------------------------------------------------------------------------
echo "[Phase 2] Grounding the Chroot Bridge & Fixing DNS..."

# 1. Fixing DNS (Phonebook)
sudo cp /etc/resolv.conf "$SQUASHFS_ROOT/etc/resolv.conf"

# 2. Creating the Virtual Bridge (The "Is /dev/pts mounted?" Fix)
# We mount the host's devices into the mansion so apt can log correctly.
for mp in /dev /dev/pts /proc /sys /run; do
    sudo mount --bind "$mp" "$SQUASHFS_ROOT$mp" 2>/dev/null || true
done

echo "[Phase 2.1] Injecting Developer Tools (Monastic Mode)..."
# We force LC_ALL=C to stop the 'locale' warnings once and for all.
sudo chroot "$SQUASHFS_ROOT" /usr/bin/env LC_ALL=C LANGUAGE=C LANG=C bash -c "
    export DEBIAN_FRONTEND=noninteractive
    apt-get update -qq
    # We add 'locales' to the install list so the ISO can have proper language later
    apt-get install -y -qq vlc geeqie ffmpeg mate-utils fonts-jetbrains-mono p7zip-full lz4 xdg-user-dirs dconf-cli pulseaudio-utils locales

    # Generate the standard English locale inside the mansion
    echo 'en_US.UTF-8 UTF-8' > /etc/locale.gen
    locale-gen -q || true

    apt-get clean
"

# 3. Closing the Bridge
# Very important: Unmount these so your host system stays stable!
for mp in /dev/pts /dev /proc /sys /run; do
    sudo umount -l "$SQUASHFS_ROOT$mp" 2>/dev/null || true
done

# ------------------------------------------------------------------------------
# [Phase 3] Absolute Asset Deployment
# ------------------------------------------------------------------------------
echo "[Phase 3] Deploying FurryOS Master Assets..."
FURRYOS_SHARE="$SQUASHFS_ROOT/usr/share/furryos"
sudo mkdir -p "$FURRYOS_SHARE"
# Ensure the payload exists before copying
if [ -d "$PROJECT_ROOT/payload/assets" ]; then
    sudo cp -ra "$PROJECT_ROOT/payload/assets/." "$FURRYOS_SHARE/"
    echo "  ✓ Wallpapers, Sounds, and Lore injected into System Root."
else
    echo "  ❌ ERROR: Assets not found in $PROJECT_ROOT/payload/assets"
    exit 1
fi

# ------------------------------------------------------------------------------
# [Phase 4] The "Sovereign" Setup Script (Internal Autopilot)
# ------------------------------------------------------------------------------
echo "[Phase 4] Generating the Sovereign Internal Controller..."
cat << 'EOF' | sudo tee "$SQUASHFS_ROOT/usr/local/bin/furryos-live-setup" > /dev/null
#!/bin/bash
# --- Runs on boot inside the ISO ---
sleep 5
L_USER=$(whoami)
L_HOME="/home/$L_USER"
SRC="/usr/share/furryos"
DEST="$L_HOME/FurryOS"

# 1. Physical Grounding (Asset Copy)
mkdir -p "$DEST"
cp -ra "$SRC/." "$DEST/"
chown -R $L_USER:$L_USER "$L_HOME"
xdg-user-dirs-update

# 2. UI Calibration (Ember-Night Developer Look)
export GSETTINGS_BACKEND=dconf
gsettings set org.mate.desktop.background picture-filename "$DEST/wallpapers/default.jpg"
gsettings set org.mate.desktop.background picture-options 'zoom'

# 🐾 Terminal Injection
PR="/org/mate/terminal/profiles/default"
dconf write $PR/use-theme-colors false
dconf write $PR/background-color "'#1A1414'"
dconf write $PR/foreground-color "'#FEE2E2'"
dconf write $PR/bold-color "'#FB8500'"
dconf write $PR/use-system-font false
dconf write $PR/font "'JetBrains Mono Medium 13'"
dconf write $PR/palette "'#1A1414:#FF4D4D:#A3CB38:#FB8500:#12CBC4:#FDA7DF:#1289A7:#D1D8E0:#57606F:#FF6B6B:#C4E538:#FFBE76:#219EBC:#ED4C67:#81ECEC:#FFFFFF'"

# 3. Audio Proclamation
(sleep 5 && paplay "$DEST/sounds/startup.ogg" || aplay "$DEST/sounds/startup.ogg") &
EOF
sudo chmod +x "$SQUASHFS_ROOT/usr/local/bin/furryos-live-setup"

# ------------------------------------------------------------------------------
# [Phase 5] Autostart & Boot Branding
# ------------------------------------------------------------------------------
echo "[Phase 5] Registering Autostart & Splash Logic..."
sudo mkdir -p "$SQUASHFS_ROOT/etc/xdg/autostart"
cat << 'EOF' | sudo tee "$SQUASHFS_ROOT/etc/xdg/autostart/furryos.desktop" > /dev/null
[Desktop Entry]
Type=Application
Name=FurryOS Setup
Exec=/usr/local/bin/furryos-live-setup
Terminal=false
X-MATE-Autostart-enabled=true
EOF

# GRUB Branding
if [ -f "$FURRYOS_SHARE/splash/splash.png" ]; then
    sudo mkdir -p "$SQUASHFS_ROOT/boot/grub"
    sudo cp "$FURRYOS_SHARE/splash/splash.png" "$SQUASHFS_ROOT/boot/grub/splash.png"
fi

# ------------------------------------------------------------------------------
# [Phase 7] Mode Switcher Core (As specified in GENOME)
# ------------------------------------------------------------------------------
echo "[Phase 7] Deploying Mode Switcher System..."
cat << 'EOF' | sudo tee "$SQUASHFS_ROOT/usr/local/bin/furryos-mode" > /dev/null
#!/bin/bash
MODE=$1
case $MODE in
  hacker) gsettings set org.mate.interface gtk-theme 'BlackMATE' ;;
  granny) gsettings set org.mate.interface font-name 'Sans 14' ;;
  ghost)  nmcli connection modify id "Wired connection 1" ipv4.dns "9.9.9.9" ;;
  *) echo "Usage: furryos-mode [hacker|granny|ghost]" ;;
esac
EOF
sudo chmod +x "$SQUASHFS_ROOT/usr/local/bin/furryos-mode"

# ------------------------------------------------------------------------------
# [Phase 8.5] The Test Drive (Stability-First Portal)
# ------------------------------------------------------------------------------
echo ""
read -p "🚗 Workspace Ready! Launch QEMU Test Drive? [y/N]: " -r TEST_DRIVE
if [[ $TEST_DRIVE =~ ^[Yy]$ ]]; then
    echo "📦 Rapid-Packing for Test (Priority: LOW to prevent host freeze)..."
    TEST_ISO="$GENERATED/test_drive.iso"
    sudo rm -f "$ISO_ROOT/live/filesystem.squashfs"

    sudo nice -n 19 ionice -c 3 mksquashfs "$SQUASHFS_ROOT" "$ISO_ROOT/live/filesystem.squashfs" -comp lz4 -noappend -b 256K -info

    # Force 'anthro' and high-res directly into the bootloader files
    # Force 'anthro' and high-res directly into the boot configuration files
    sudo find "$ISO_ROOT" -name "*.cfg" -type f -exec sed -i "s/boot=live/boot=live live-username=anthro vga=791/g" {} +

    # 🎨 BIOS Boot Splash Fix (ISOLINUX)
    echo "🖼️ Branding the BIOS threshold..."
    # Debian's BIOS menu looks for splash.png in the isolinux folder
    if [ -f "$FURRYOS_SHARE/splash/splash.png" ]; then
        sudo mkdir -p "$ISO_ROOT/isolinux"
        sudo cp "$FURRYOS_SHARE/splash/splash.png" "$ISO_ROOT/isolinux/splash.png"

        # We also need to tell the config to actually display it
        sudo sed -i 's/menu background.*/menu background splash.png/g' "$ISO_ROOT/isolinux/stdmenu.cfg" 2>/dev/null || true
        echo "  ✓ BIOS splash applied."
    fi

    echo "💿 Grounding Boot Records..."
    sudo nice -n 19 xorriso -as mkisofs -iso-level 3 -full-iso9660-filenames -volid "FurryOS" \
        -eltorito-boot isolinux/isolinux.bin -eltorito-catalog isolinux/boot.cat \
        -no-emul-boot -boot-load-size 4 -boot-info-table -output "$TEST_ISO" "$ISO_ROOT" 2>/dev/null

    echo "🚀 Portal Open. High-Resolution Mode Active."
    sudo qemu-system-x86_64 -cdrom "$TEST_ISO" -m 2G -smp 4 -enable-kvm -vga virtio -display gtk,gl=on,zoom-to-fit=on -usb -device usb-tablet

    sudo rm -f "$TEST_ISO"
fi

# ------------------------------------------------------------------------------
# [Phase 9/10] High-Density XZ Packing (The Final Sovereign Release)
# ------------------------------------------------------------------------------
echo ""
read -p "🚀 Finalize Build: Pack XZ ISO? [P/e]: " -n 1 -r NEXT_STEP
echo ""
if [[ ${NEXT_STEP,,} != "e" ]]; then
    echo "[Phase 9] Repacking SquashFS (High-Density XZ Mode)..."
    sudo rm -f "$ISO_ROOT/live/filesystem.squashfs"
    sudo nice -n 19 mksquashfs "$SQUASHFS_ROOT" "$ISO_ROOT/live/filesystem.squashfs" \
        -comp xz -b 1048576 -mem "${SQUASH_MEM}G" -noappend >/dev/null

    echo "[Phase 10] Finalizing bootable ISO..."
    # Force username 'anthro' into boot config
    sudo find "$ISO_ROOT" -name "*.cfg" -type f -exec sed -i 's/boot=live/boot=live live-username=anthro/g' {} +

    OUTPUT_ISO="$OUTPUT_DIR/furryos-gen2.1-v2.iso"
    MBR_BIN=$(find /usr/lib -name isohdpfx.bin 2>/dev/null | head -n 1 || echo "")

    # Force 'anthro' and high-res directly into the boot configuration files
    sudo find "$ISO_ROOT" -name "*.cfg" -type f -exec sed -i "s/boot=live/boot=live live-username=anthro vga=791/g" {} +

    # 🎨 BIOS Boot Splash Fix (ISOLINUX)
    echo "🖼️ Branding the BIOS threshold..."
    # Debian's BIOS menu looks for splash.png in the isolinux folder
    if [ -f "$FURRYOS_SHARE/splash/splash.png" ]; then
        sudo mkdir -p "$ISO_ROOT/isolinux"
        sudo cp "$FURRYOS_SHARE/splash/splash.png" "$ISO_ROOT/isolinux/splash.png"

        # We also need to tell the config to actually display it
        sudo sed -i 's/menu background.*/menu background splash.png/g' "$ISO_ROOT/isolinux/stdmenu.cfg" 2>/dev/null || true
        echo "  ✓ BIOS splash applied."
    fi

    sudo xorriso -as mkisofs -iso-level 3 -full-iso9660-filenames -volid "FurryOS" \
        -eltorito-boot isolinux/isolinux.bin -eltorito-catalog isolinux/boot.cat -no-emul-boot \
        -boot-load-size 4 -boot-info-table ${MBR_BIN:+-isohybrid-mbr "$MBR_BIN"} \
        -output "$OUTPUT_ISO" "$ISO_ROOT" 2>/dev/null

    echo "✅ MASTERPIECE CREATED: $OUTPUT_ISO"
fi

DURATION=$(($(date +%s) - BUILD_START_TIME))
echo "⏱️ Total build time: $((DURATION / 60))m $((DURATION % 60))s"
